// 实现这个项目的构建任务
// 关于实现思路，还是以注释的形式直接写到代码里了= =

//1. 确定需要构建的文件，选取对应的插件
//   *js, *.scss, *.html, fonts&images
//2. 构建开发服务器
//3. 监听文档变化自动编译

const { src, dest, watch } = require("gulp");
const del = require("del");
const browserSync = require("browser-sync");
const loadPlugins = require("gulp-load-plugins");
const plugins = loadPlugins();
const bs = browserSync.create();

//构建前清除已存在的文件
const clean = () => {
  return del(["dist", "dev"]);
};

//处理sass文件
const style = () => {
  return src("src/assets/styles/*.scss", { base: "src" })
    .pipe(plugins.sass({ outputStyle: "expanded" }))
    .pipe(sass().on('error', sass.logError))
    .pipe(dest("dev"))
    .pipe(bs.reload({ stream: true }));
};

//处理js文件
const script = () => {
  return src("src/assets/scripts/*.js", { base: "src" })
    .pipe(plugins.babel({ presets: ["@babel/preset-env"] }))
    .pipe(dest("dev"))
    .pipe(bs.reload({ stream: true }));
};

//处理html文件
const page = () => {
  return src("src/*.html", { base: "src" })
    .pipe(plugins.swig({ data, defaults: { cache: false } })) // 防止模板缓存导致页面不能及时更新
    .pipe(dest("dev"))
    .pipe(bs.reload({ stream: true }));
};

//静态资源压缩
const static = () => {
  return src(["src/assets/images/**", "src/assets/fonts/**"], { base: "src" })
    .pipe(plugins.imagemin())
    .pipe(dest("dist"));
};

//其余不需要处理的资源
const others = () => {
  return src("public/**", { base: "public" }).pipe(dest("dist"));
};

//开发服务器
const serve = () => {
  watch("src/assets/styles/*.scss", style);
  watch("src/assets/scripts/*.js", script);
  //watch("src/*.html", page);
  watch(
    ["src/assets/images/**", "src/assets/fonts/**", "public/**"],
    bs.reload
  );

  bs.init({
    notify: false,
    port: 8088,
    server: {
      baseDir: ["dev", "src", "public"],
      routes: {
        "/node_modules": "node_modules",
      },
    },
  });
};

//构建html，替换html模板里的路径
const useref = () => {
  return (
    src("dev/*.html", { base: "dev" })
      .pipe(plugins.useref({ searchPath: ["dev", "."] }))
      .pipe(plugins.if(/\.js$/, plugins.uglify()))
      .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
      .pipe(
        plugins.if(
          /\.html$/,
          //压缩文件
          plugins.htmlmin({
            collapseWhitespace: true,
            minifyCSS: true,
            minifyJS: true,
          })
        )
      )
      .pipe(dest("dist"))
  );
};

const compile = parallel(style, script, page);

// 上线之前执行的任务
const build = series(
  clean, parallel(
    series(compile, useref), 
    static, 
    others)
);

//开发
const develop = series(compile, serve);

module.exports = {
  clean,
  build,
  develop,
};
